package demo3;

/**
 * 在多个实例中在使用锁对象
 */

public class Text03 {
    public static void main(String[] args) throws InterruptedException {
        Counter03  counter1 = new Counter03();
        Counter03  counter2 = new Counter03();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter1.increase();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter2.increase();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("count：" + counter1.count);
    }
}


class Counter03 {
    // 初始值为0
    public static int count = 0;

    // 单独定义一个对象作为锁对象用
    Object locker = new Object();

    /**
     * 累加方法
     *
     */

    public void increase () {
        // 只定义锁代码块
        synchronized (locker) {
            count++;
        }
    }
}


